package com.hs.mod_main

import android.content.res.Configuration
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.hs.auth.RegisterByFingerDialogFragment
import com.hs.common.RouteIndex
import com.hs.common.UserInitInfo
import com.hs.common.dto.SysDeptDto
import com.hs.common.dto.SysRoleDto
import com.hs.common.dto.SysUserDto
import com.hs.common.provider.SysUserProvider
import com.hs.common.repository.IDeptRepository
import com.hs.common.repository.IRoleRepository
import com.hs.common.repository.IUserRepository
import com.hs.framework.base.BaseDataBindActivity
import com.hs.mod_main.databinding.ActivityMainBinding
import com.hs.room.model.sys.SysLog
import com.hs.room.repository.service.ISysLogRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject


@Route(path = RouteIndex.mainActivity)
@AndroidEntryPoint
class MainActivity : BaseDataBindActivity<ActivityMainBinding>() {


    @Inject
    lateinit var userService: IUserRepository

    @Inject
    lateinit var roleService: IRoleRepository

    @Inject
    lateinit var deptService: IDeptRepository

    @Inject
    lateinit var sysLogRepository: ISysLogRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SysUserProvider.removeUser()
    }


    override fun initView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        initUserInfo()
        val displayMetrics = DisplayMetrics()
//        // 获取窗口管理器服务
//        // 获取窗口管理器服务
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics)
        val widthPixels = displayMetrics.widthPixels
        val heightPixels = displayMetrics.heightPixels
        val density = displayMetrics.density
        val densityDpi = displayMetrics.densityDpi
        Log.d("ScreenResolution", "屏幕宽度（像素）: $widthPixels") // 1024
        Log.d("ScreenResolution", "屏幕高度（像素）: $heightPixels")//  504
        Log.d("ScreenResolution", "屏幕密度: $density") // 2.0
        Log.d("ScreenResolution", "屏幕密度DPI: $densityDpi") // 320
//        val resources = resources
//        val config: Configuration = resources.configuration
//        val smallestScreenWidthDp: Int = config.smallestScreenWidthDp
//        ToastUtils.toast("" + smallestScreenWidthDp)
//        println("${smallestScreenWidthDp}")
//        userService.getAllUsers()

        observerAllUser()


    }

    /**
     * 观察用户信息
     */
    private fun observerAllUser(){


        lifecycleScope.launch{
            userService.getAllUsers().collect{
                for (sysUserDto in it) {
                    println("${sysUserDto}")
                }
//                RegisterByFingerDialogFragment.show(supportFragmentManager,it[0],object : RegisterByFingerDialogFragment.AuthListener{
//                    override fun onAuthResult(sysUserDto: SysUserDto) {
//                        sysUserDto.let {
//                            // 有数据返回
//                            println("账号密码登录 ：  ${sysUserDto.userName}")
//                        }?: run {
//                            // 返回控
//                        }
//                    }
//                } )
            }
        }

//        lifecycleScope.launch{
//            sysLogRepository.getSysLogs().collect{
//                for (sysLog in it) {
//                    println("${sysLog}")
//                }
//            }
//        }
    }

    private fun initUserInfo(){

        lifecycleScope.launch(Dispatchers.IO){
            UserInitInfo.roleMap.forEach{(k,v)->
                run {
                    roleService.selectByCode(UserInitInfo.sysTemNo) ?: run {
                        val role = SysRoleDto(roleName = k, code = v, sysTemNo = UserInitInfo.sysTemNo)
                        roleService.insertRole(role)
                    }
                }
            }
        }

        lifecycleScope.launch(Dispatchers.IO){
            UserInitInfo.deptMap.forEach{(k,v)->
                run {
                    deptService.selectByCode(UserInitInfo.sysTemNo) ?: run {
                        val dept = SysDeptDto(deptName = k, code = v, sysTemNo = UserInitInfo.sysTemNo)
                        deptService.insertDept(dept)
                    }
                }
            }
        }

        lifecycleScope.launch(Dispatchers.IO){
            userService.initUser(UserInitInfo.sysTemNo)
        }



    }

    override fun onNavigateUp(): Boolean {
        Log.d("onSupportNavigateUp","=======================onNavigateUp====================")
        return super.onNavigateUp()
    }


    private var exitTime : Long = 0

    override fun onBackPressed() {
//        super.onBackPressed()
        Log.d("onSupportNavigateUp","=======================onBackPressed====================")
        if (System.currentTimeMillis() - exitTime < 3000){
            super.onBackPressed()
        }else{
            Toast.makeText(this@MainActivity,"请再按一次退出",Toast.LENGTH_SHORT).show()
            exitTime = System.currentTimeMillis()
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        Log.d("onSupportNavigateUp","===========================================")
        return super.onSupportNavigateUp()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 移除当前用户
        SysUserProvider.removeUser()
    }

}